mini.parse();
var projectName = mini.get("projectName").getValue();
var grid1 = mini.get("old_equipment_list_datagrid");//报修设备
var grid2 = mini.get("new_equipment_list_datagrid");//出库设备
var grid3 = mini.get("confirm_equipment_list_datagrid");//确认安装设备
var grid4 = mini.get("service_equipment_list_datagrid");//可维修设备
var grid5 = mini.get("scrap_equipment_list_datagrid");//报废设备
var org_id = mini.get("org_id");
var shop_name = mini.get("shop_name");
var shop_id = mini.get("shop_id");
var shop_addr = mini.get("shop_addr");
var check_people_id = mini.get("check_people_id");
var repair_people_id = mini.get("repair_people_id");
var repair_people_name = mini.get("repair_people_name");
var confirm_people_id = mini.get("confirm_people_id");
var confirm_people_name = mini.get("confirm_people_name");
var storage_addr = mini.get("storage_addr");
var storage_addr_id = mini.get("storage_addr_id");
var storage_attr = mini.get("storage_attr");
var storage_name = mini.get("storage_name");
var storage_id = mini.get("storage_id");
var storage_people_name = mini.get("storage_people_name");
var storage_people_id = mini.get("storage_people_id");
var repair_time=mini.get("repair_time");
var confirm_time=mini.get("confirm_time");
var has_bad_goods=mini.get("has_bad_goods");
var taskKey=mini.get("taskKey").getValue();
var businessKey = mini.get("wo_no").getValue();
var shopId = '';
var physicalStorageId = '';
var storageId = '';
var url = '';
var person = '';
var orgId = '';


hideOpbutton();
function hideOpbutton(){
	console.log(taskKey);
	if(taskKey == "start" || taskKey == "usertask1" || taskKey == "usertask2" || taskKey == "usertask3" || taskKey == "usertask4"){
		$("#confirm_time").hide();
	}
	if(taskKey == "usertask4"){
		$("#T_EQUIPMENT_SERVICE0710_addbt_old_equipment_list_datagrid").hide();
		$("#T_EQUIPMENT_SERVICE0710_delbt_old_equipment_list_datagrid").hide();
	}
	$("#T_EQUIPMENT_SERVICE0710_addbt_confirm_equipment_list_datagrid").hide();
	$("#T_EQUIPMENT_SERVICE0710_delbt_confirm_equipment_list_datagrid").hide();
	$("#T_EQUIPMENT_SERVICE0710_addbt_new_equipment_list_datagrid").hide();
	$("#T_EQUIPMENT_SERVICE0710_delbt_new_equipment_list_datagrid").hide();
}
//确认时间赋值
function setConfirmTime(){
	$.ajax({
		url : projectName+"/UtilAdmin/getCurrentTime",
		type : 'post',
		async:false,
		cache : false,
		success : function(data) {
			confirm_time.setValue(data);
		},
	        error : function(jqXHR, textStatus, errorThrown) {	   
			mini.alert(jqXHR.responseText);
			status =  false;
		}
	});
}

//选择店铺时,加载店铺地址
function onShopChange(){
	shop_name.setValue(shop_id.text);
	var item=shop_id.getSelected();
	shop_addr.setValue(item.contactAddress);
	repair_people_id.setValue(item.engineeringStaffId);
	repair_people_name.setValue(item.engineeringStaff);
	confirm_people_id.setValue(item.supportStaffId);
	confirm_people_name.setValue(item.supportStaff);
	shopId = shop_id.getValue();
	if (shop_addr.setIsValid) shop_addr.setIsValid(true);
}

//选择店铺地址时校验是否选择了店铺
function checkShopId(){
    shopId = shop_id.getValue();
    if(!shopId){
        mini.alert("请选择店铺名称");
    }else{
        var url = projectName + "/ShShopAdmin/querySupEnByShopId?shopNumId=" + shopId;
        repair_people_id.load(url);
    }
}

//选择维修人员时给维修人员id和name赋值
function onPeopleChange(){
    repair_people_name.setValue(repair_people_id.text);
}


//选择仓库负责人时校验是否选择了逻辑仓
function onPersonCheck(){
	person = storage_id.getValue();
  	if(!person){
  		mini.alert("请选择仓库");
  	}
}

//选择物理仓时加载逻辑仓  给物理仓name赋值   清空逻辑仓及负责人
function onPhyStorageChange(){
	storage_addr.setValue(storage_addr_id.text);
	storage_name.setValue("");
	storage_id.setValue("");
	storage_people_name.setValue("");
	storage_people_id.setValue("");
	physicalStorageId = storage_addr_id.getValue();
  if(physicalStorageId){
		url = projectName + "/StStorageAdmin/findStStorageList?physicalStorageId=" + physicalStorageId;
		storage_id.load(url);
  }
}

//选择逻辑仓时加载仓库负责人 给逻辑仓name赋值
function onStorageChange(){
	storage_name.setValue(storage_id.text);
	var item = storage_id.getSelected();
	storage_attr.setValue(item.storageType);
	storage_people_id.setValue(item.directorId);
	storage_people_name.setValue(item.directorName);
	storage_people_name.validate();
}

//审批结果如果为不通过,则必须填写审批意见
function onSelectResult1(e){
	onSelectResult(e,"check_memo");
	var re = e.value;
	if (re && re == '1')  showSupply();
	if (re && re == '0')  hideSupply();
}

//显示出库仓库信息
function showSupply() {
	storage_addr_id.show();
	storage_id.show(); 
	storage_people_name.show();
}

// 隐藏出库仓库信息
function hideSupply() {
	storage_addr.setValue("");
	storage_addr_id.setValue(""); 
	storage_attr.setValue(""); 
	storage_name.setValue(""); 
	storage_id.setValue(""); 
	storage_people_name.setValue(""); 
	storage_people_id.setValue(""); 
	storage_addr_id.hide();
	storage_id.hide(); 
	storage_people_name.hide();
}

//确认是否通过
function onSelectResult2(e){
	onSelectResult(e,"confirm_memo");
}

//审批结果如果为不通过,则必须填写审批意见
function onSelectResult3(e){
	onSelectResult(e,"scrap_memo");
}

function onSelectResult(e,memoName){
	var re = e.value;
	var c = mini.get(memoName);
	if( re && re == '1'){
		c.setRequired(false);
		c.validate();
		c.setEmptyText("");
		if (e.setIsValid) e.setIsValid(true);
	}
	if( re && re == '0'){
		mini.get(memoName).setRequired(true);
		c.setEmptyText("请输入审批不通过的原因");
	}
}

var windowsFlag = false;
//选择逻辑仓时校验是否选择了物理仓
function onAddrCheck(){
	physicalStorageId = storage_addr_id.getValue();
  	if(!physicalStorageId){
		if (!windowsFlag) {
			mini.alert("请选择仓库地点", "", function() {
				windowsFlag = false;
			});
			windowsFlag = true;
		}
  	}
}

//usertask1  同步报修设备到出库设备和确认设备表  相关代码在submitPage.js  line166--122
//usertask2  审核如果驳回，刚清除报修  出库  确认设备报表
function beforeSend(){
	var shopId = shop_id.getValue();
	var storageId = storage_id.getValue();
	if(taskKey == "start" || taskKey== "usertask1"){
		queryCheckPeople();
		if(!checkGrid(grid1)){ return false; }//校验报修设备非空
		if(!checkCheckPeople()){ return false;}
		try {
			syncGrid1toGrid2();
			mini.get('check_result').setValue('1');
		} catch (e) {
			mini.alert("同步设备列表出错！"); return false;
		}
	}
	if(taskKey== "usertask2"){
		var e = mini.get("check_result");
		onSelectResult(e,"check_memo");
		var re = e.getValue();
		if(re && re == '0'){
			hideSupply();
			}
		if(validateform2()){
		if(re && re == '0'){
				var gridArr = [grid1,grid2];
				delGridRow(gridArr);
			}
		}
	}
	if(taskKey== "usertask3"){
		if(!checkGrid(grid2)) {return false;} //校验出库设备非空
		if(!checkCount(buildCheckCountParam2())) {return false; }//校验出库条码数
		//出库判断设备是否在库
		if (!checkBarcodeStatus(mini.get("wo_no").getValue(),mini.get("storage_id").getValue(), "2")) {
			return false;
		}
	}
	if(taskKey== "usertask4"){
		if(!checkCount(buildCheckCountParam1())) {return false; }//校验报修条码数
		try {
			syncGrid1toGrid3();
		} catch (e) {
			mini.alert("同步设备列表出错！"); {return false;}
		}
	}
	if(taskKey== "usertask5"){
		setConfirmTime();
		var c = mini.get("confirm_result").getValue();
		if(c == '1'){
			if(!checkGrid(grid3)){ return false; }//校验确认设备非空
			if(!compareGrid(grid2.getData(),grid3.getData())){ return false;}//比较确认子表和出库子表数据
			if(!checkCount3()){ return false;} //校验确认条码数
		}else if (c == '0'){
			delGridRow([grid3]);
		}
	}
	if(taskKey== "usertask6"){
		if((!checkRows(grid4)) && (!checkRows(grid5))){
			mini.alert("请填写表格信息");
			return false;
		} 
		if(checkRows(grid4)&&!checkCount(buildCheckCountParam4())){ return false;}
		if(checkRows(grid5)&&!checkCount(buildCheckCountParam5())){ return false;}
		if(!checkCount_()) {return false;}
		if(!checkHasBadGoods()) {return false;}
	}
	return true;
}
/** 提交验证条码状态**/
function checkBarcodeStatus(businessKey,storageNumId,statusNumId){
	var flag = true;
	$.ajax({
		url:projectName+'/InventoryEqAdmin/checkBarcodesForSubmit',
		type:'post',
		dataType:'json',
		cache:false,
		async:false,
		data:{businessKey:businessKey,storageNumId:storageNumId,statusNumId:statusNumId},
		success: function(response){
			if (response.status == "1") {
				flag =  true;
			}else{
				mini.alert(response.message);
				flag =  false;
			}
		},error:function(){
			mini.alert("验证条码状态请求失败");
			flag =  false;
		}
	});
	return flag;
}
//同步标记，驳回的单子在form.js中体现 ，第一次申请的单子由submitPage.js完成  报修设备同步到出库设备列表
function syncGrid1toGrid2(){
	mini.get("htmlValue").setValue("syncGrid2_service");
}

//出库设备同步到确认设备列表 
function syncGrid1toGrid3(){
	mini.get("htmlValue").setValue("syncGrid3_service");
}

//清除子表数据
function delGridRow(gridArr){
	for (var i = 0; i < gridArr.length; i++) {
		var gird = gridArr[i];
		var l = gird.getData().length;
		for (var j = l-1; j >= 0; j--) {
			var row = gird.getRow(j);
			gird.removeRow(row);
		}
	}
}

//校验入库数量与拆除设备数量是否一致
function checkCount_(){
	//判断数量是否相等
	var data1 = grid1.getData();
	var data4 = grid4.getData();
	var data5 = grid5.getData();
	var newCount = 0;
    var repCount = 0;
	for (var i =0;i < data1.length;i++ ){
		newCount = parseInt(newCount)+ parseInt(data1[i].EQ_NUM);
	}
	for (var j =0;j < data4.length;j++ ){
		repCount = parseInt(repCount) + parseInt(data4[j].EQ_NUM);
	}
	for (var k =0;k < data5.length;k++ ){
		repCount = parseInt(repCount) + parseInt(data5[k].EQ_NUM);
	}
	if (parseInt(newCount) != parseInt(repCount)){
		mini.alert("入库数量与报修拆除设备数量不一致");
		return false;	
	}
	return true;
}

//是否存在报废品
function setHasBadGoods(){
	var rows = grid5.getData();
	if(rows.length > 0){
		has_bad_goods.setValue('1');				
	}else{
		has_bad_goods.setValue('0');
	}
}

//校验has_bad_goods是否赋值
function checkHasBadGoods(){
	has_bad_goods.setValue('');
	setHasBadGoods();
	var hasBadGoods = has_bad_goods.getValue();
	if(!hasBadGoods){
		mini.alert("获取报废设备信息出错！");
		return false;
	}
	return true;
}

//校验两个grid表格数据是否相同  
function compareGrid(data,data1){
	outer:
	for (var i = 0; i < data.length; i++) {
		var flag = false;
		inter:
		for (var j = 0; j < data1.length; j++) {
			if (data[i].EQ_TYPE_ID == data1[j].EQ_TYPE_ID){
				flag = true;
				break inter;
			}
		}
		if (!flag) {
			mini.alert("确认设备清单与报修设备清单不一致");
			return false;
		}
	}
	return true;
}

//查询审核人员  同组织机构的设备主管
function queryCheckPeople(){
	orgId = org_id.getValue();
	if(orgId){
		$.ajax({
			url : projectName + "/RoleUserAdmin/queryCheckPeople?orgId=" + orgId,
			dataType : 'json',
			async : false,
			success : function(data) {
				if (data.status == '1') {
					check_people_id.setValue(data.message);
				} else {
					mini.alert("查询交接单审核人员出错!");
				}
			},
			error : function() {
				mini.alert("查询审核人员出错啦!");
			}
		});
	}
}

//校验子表非空并提示
function checkGrid(gridPar){
	var data = gridPar.getData();
	if (data.length > 0) { return true;}
	mini.alert("请添加子表设备信息");
	return false;
}

// 验证表格是否有数据
function checkRows(gridPar){
	var data = gridPar.getData();
	if (data.length>0) { return true;}
	return false;
}

//校验审核人  客服经理
function checkCheckPeople(){
	var checkPeopleId = check_people_id.getValue();
	if(!checkPeopleId){
		mini.alert("系统中没有配置处理维修单审核的工作流人员，禁止提交！");
		return false;
	}
	return true;
}
///////////////////////////组装查询设备条码数 需要的参数/////////////////////////////////////
function buildCheckCountParam1(){ return buildCheckCountParam_(grid1,'2','2');} 
function buildCheckCountParam2(){ return buildCheckCountParam_(grid2,'2','1');}
function buildCheckCountParam4(){ return buildCheckCountParam_(grid4,'1','2');}
function buildCheckCountParam5(){ return buildCheckCountParam_(grid5,'1','3');}

function buildCheckCountParam_(gridPar, statusNumId, attributeNumId){
	var arr = [];
	var griddata = gridPar.getData();
	for (var i = griddata.length - 1; i >= 0; i--) {
		var obj = {
			businessKey : mini.get("wo_no").getValue(),
			equipmentType : griddata[i].EQ_TYPE_ID,
			num : griddata[i].EQ_NUM,
			statusNumId : statusNumId,
			attributeNumId : attributeNumId 
		};
		arr.push(obj);
	}
	return mini.encode(arr);
}

//校验设备条码数
function checkCount(data,url){
	var flag = false;
	$.ajax({
		url:projectName + '/PurBarcodeAdmin/validateCount',
		type:'post',
		dataType:'json',
		cache:false,
		async:false,
		data:{list:data},
		success: function(response){
			if (response.status == "1") {
				flag =  true;
			}else{
				mini.alert(response.message);
			}
		},error:function(){
			mini.alert("验证条码数量请求失败");
		}
	});
	return flag;
}

//校验确认设备条码
function checkCount3(){
	var flag = false;
	var checkResult = mini.get("check_result").getValue();
	if(checkResult == '1'){
		var wono = mini.get("wo_no").getValue();
		$.ajax({
			url:projectName+'/PurBarcodeAdmin/checkInstallbarcode',
			type:'post',
			dataType:'json',
			cache:false,
			async:false,
			data:{businessKey: wono,statusNumId:'2',attributeNumId:'1'},
			success: function(response){
				if (response.status == "1") {
					flag =  true;
				}else{
					mini.alert('确认设备的条码与出库设备的条码不一致');
				}
			},
			error:function(){
				mini.alert("出错啦!");
			}
		});
	}
	if(checkResult == '0') flag = true;//确认驳回  不需要校验条码
	return flag;
}

//////////////////////添加设备信息////////////////////////////////////
function addEquipmentList1(){ addEquipmentList(grid1);}
function addEquipmentList2(){ addEquipmentList(grid2);}
function addEquipmentList3(){ copyNewToConfirm(grid2,grid3);}
function addEquipmentList4(){ addEquipmentList_(grid4);}
function addEquipmentList5(){ addEquipmentList_(grid5);}

//可维修和报废设备新增
function addEquipmentList_(paramGrid){
	if(!validateform2()){
		return;
	}
	mini.open({
		url: projectName+"/TableDefineAdmin/addequipment_list_applyForUsage",
			title: "新增", width: 700, height: 300,
			onload: function () {
			var iframe = this.getIFrameEl();
			var action = "new";
			iframe.contentWindow.CheckEventSubTable(action);
        },
        ondestroy: function (action) {
			if(typeof(action)=="object" ){				
				var eqTypeId = action.EQ_TYPE_ID;
				var eqNum = action.EQ_NUM;
				if(eqTypeId){										
					var rows = paramGrid.getData();
					for(var i=0,l=rows.length;i<l;i++){
					    var row = rows[i];
					    if(row.EQ_TYPE_ID == eqTypeId){
							mini.alert("列表中已存在该设备类型");
							return;
					    }
					}
					var rowsRefer = grid1.getData();
					var existFlag = false; 
					for(var i=0,l=rowsRefer.length;i<l;i++){
					    var rowRefer = rowsRefer[i];
					    if(rowRefer.EQ_TYPE_ID == eqTypeId){
					    	existFlag = true;
					    	if(parseInt(rowRefer.EQ_NUM) < parseInt(eqNum)){
					    		mini.alert("数量不能超过报修设备数量");
					    		return;
					    	}
							break;
					    }
					}
					if(!existFlag){
						mini.alert("只能选择报修的设备类型");
						return;
					}
					paramGrid.addRow(action);								
				}
			}
       }
   });
}

//新增确认设备     同步出库子表到确认子表
function copyNewToConfirm(gridOriginal,gridCopy){
	if (!validateform2())  return;
	var data1 = mini.clone(gridOriginal.getData());
	var data2 = gridCopy.getData();
	addDataToGrid(data1, data2, gridCopy);
}

//同步两张子表   data 源表格数据      dataOther 目标表格数据     grid 目标表格
function addDataToGrid(data, dataOther, gridCopy) { 
	for (var i = 0; i < data.length; i++) {
		var hasFlag = false;
		for (var j = 0; j < dataOther.length; j++) {
			if (dataOther[j].EQ_TYPE_ID == data[i].EQ_TYPE_ID)
				hasFlag = true;
		}
		if (!hasFlag) {
			gridCopy.addRow(data[i]);
		}
	}
}

function addEquipmentList(paramGrid){
	if(!validateform2()){
		return;
	}
	mini.open({
		url: projectName+"/TableDefineAdmin/addequipment_list_applyForUsage",
			title: "新增", width: 700, height: 300,
			onload: function () {
			var iframe = this.getIFrameEl();
			var action = "new";
			iframe.contentWindow.CheckEventSubTable(action);
        },
        ondestroy: function (action) {
			if(typeof(action)=="object" ){				
				var eqTypeId = action.EQ_TYPE_ID;
				if(eqTypeId){										
					var rows = paramGrid.getData();
					for(var i=0,l=rows.length;i<l;i++){
					    var row = rows[i];
					    if(row.EQ_TYPE_ID == eqTypeId){
							mini.alert("列表中已存在该设备类型");
							return;
					    }
					}
					paramGrid.addRow(action);								
				}
			}
       }
   });
}

//////////////////////查看设备条码////////////////////////////////////
function queryBarCode1(uid){ queryBarCode(grid1,uid,'2','2','/PurBarcodeAdmin/barCodeView');}//
function queryBarCode2(uid){ queryBarCode(grid2,uid,'2','1','/PurBarcodeAdmin/barCodeView');} 
function queryBarCode3(uid){ queryBarCode(grid3,uid,'0','1','/PurBarcodeAdmin/barCodeView');}
function queryBarCode4(uid){ queryBarCode(grid4,uid,'1','2','/PurBarcodeAdmin/purBarcodeShopView');}
function queryBarCode5(uid){ queryBarCode(grid5,uid,'1','3','/PurBarcodeAdmin/purBarcodeOutScrapCallView');}

function queryBarCode(gridPara,uid,statusNumId,attributeNumId,url){
	var c = gridPara.getRowByUID(uid);
	var businessKey = mini.get("wo_no").getValue();
	var eqTypeId=c.EQ_TYPE_ID;
	var data = {
		businessKey : businessKey,
		eqTypeId : eqTypeId,
		statusNumId : statusNumId,
		attributeNumId : attributeNumId
	};
	mini.open({
        url: projectName + url,
        title: '查看条码', width: 700, height: 500,
        onload: function () {
            var iframe = this.getIFrameEl();
            iframe.contentWindow.setData(data);
        }
    });
}

//////////////////////编辑设备条码////////////////////////////////////
function editBarCode1(uid){ editBarCode(grid1,uid,shop_id.getValue(),'2','2','usertask4','/PurBarcodeAdmin/outEditPage');}
function editBarCode2(uid){ editBarCode(grid2,uid,storage_id.getValue(),'2','1','usertask3','/PurBarcodeAdmin/outEditPage');}
function editBarCode3(uid){ editBarCode(grid3,uid,shop_id.getValue(),'0','1','usertask5','/PurBarcodeAdmin/shopConfirmEditPage');}
function editBarCode4(uid){ editBarCode(grid4,uid,shop_id.getValue(),'1','2','usertask6','/PurBarcodeAdmin/shopRepairAdd');}
function editBarCode5(uid){ editBarCode(grid5,uid,shop_id.getValue(),'1','3','usertask6','/PurBarcodeAdmin/purBarcodeOutScrapCallAdd');}

//编辑新设备条码
function editBarCode(gridPara,uid,storageNumId,statusNumId,attributeNumId,edit_taskKey,url){
	if(taskKey != edit_taskKey){
		mini.alert("该流程不允许编辑条码");
		return ;
	}
	var c = gridPara.getRowByUID(uid);
	var businessKey = mini.get("wo_no").getValue();
	var eqTypeId=c.EQ_TYPE_ID;
	var eqTypeName=c.EQ_TYPE_NAME;
	var eqNum=c.EQ_NUM;
	var data = {
		businessKey : businessKey,
		eqTypeId : eqTypeId,
		eqTypeName : eqTypeName,
		eqNum : eqNum,
		storageNumId:storageNumId,
		statusNumId : statusNumId,
		attributeNumId : attributeNumId
	};
	data.dymcformId = 'K_DYMCFORM_20170626094847';
	mini.open({
        url: projectName + url,
        title: '编辑条码', width: 700, height: 500,
        onload: function () {
            var iframe = this.getIFrameEl();
            iframe.contentWindow.setData(data);
        }
    });
}

///////////////////////////删除设备时同时删除条码/////////////////////////////////////////
function delRow1(e){ delRow_(e,grid1,'2','2');}
function delRow2(e){ delRow_(e,grid2,'2','1');}
function delRow3(e){ delRow_(e,grid3,'0','1');}
function delRow4(e){ delRow_(e,grid4,'1','2');}
function delRow5(e){ delRow_(e,grid5,'1','3');}

function delRow_(e,gridPar,statusNumId,attributeNumId){
	if(batchDelBarcode(gridPar,statusNumId,attributeNumId)){
		delRow(e);
	}
}

function batchDelBarcode(gridPar,statusNumId,attributeNumId){
	var flag = true;
	try {
		var businessKey = mini.get("wo_no").getValue();
		var rows = gridPar.getSelecteds();
		for (var i = 0; i < rows.length; i++) {
			var equipmentType = rows[i].EQ_TYPE_ID;
			var param = {businessKey:businessKey,equipmentType:equipmentType,statusNumId:statusNumId,attributeNumId:attributeNumId};
			flag = delBarcode(param, flag);
		}
	} catch (e) {
		console.log(e);
		flag = false;
		mini.alert("出错啦！");
	}
	return flag;
}

function delBarcode(param, flag){
	if(flag){
		$.ajax({
			url: projectName + "/PurBarcodeAdmin/delBarcodeByBusKey",
			type:'post',
			dataType:'json',
			async:false,
			data: param,
			success:function(response){
				if(response.status==1){
				}else{
					flag = false;
					mini.alert(response.message);
				}
			},
			error:function(){
				flag = false;
				mini.alert("出错啦！");
			}
		});
	}
	return flag;
}

//校验必填项
function validateform2() {
	var form_temp = new mini.Form("form2");
	form_temp.validate();
	if (form_temp.isValid() == false) {
		mini.alert("请完善表单信息");
		return false;
	}
	return true;
}